package com.easyOrder.core.json;

import com.easyOrder.core.exception.ApplicationErrorCode;
import com.easyOrder.core.exception.ApplicationException;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

public class JsonWrapper<T> {
	
	private String code;
	
	private String msg;
	
	private long version;
	
	private T data;
	
	public JsonWrapper(Throwable ex) {
		if (ex instanceof ApplicationException) {
			ApplicationException gex = (ApplicationException)ex;
			this.code = gex.getCode();
			this.msg = gex.getReasoning();
		} else {
			this.code = ApplicationErrorCode.UnKnowException.getCode();
			this.msg = ex.getMessage();
		}
	}
	
	public JsonWrapper(T result) {
		this.data = result;
		code = "0";
		msg = "";
	}
	
	public JsonWrapper(T result, String message) {
		this.data = result;
		code = "0";
		msg = message;
	}
	
	public JsonWrapper(T result, long version) {
		this.data = result;
		code = "0";
		msg = "";
		this.version = version;
	}
	
	public static String getStackTrace(Throwable throwable) {  
	    if (throwable == null) {
	    	return "";  
	    }
	    String stackTrace = throwable.getStackTrace().toString();  
	    try {  
	        Writer writer = new StringWriter();  
	        PrintWriter printWriter = new PrintWriter(writer);  
	        throwable.printStackTrace(printWriter);       
	        printWriter.flush();  
	        writer.flush();  
	        stackTrace = writer.toString();  
	        printWriter.close();              
	        writer.close();  
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }  
	    return stackTrace;  
	}
	
	public JsonWrapper() {
		super();
	}
	
	public long getVersion() {
		return version;
	}

	public void setVersion(long version) {
		this.version = version;
	}

	/**
	 * @return the code
	 */
	public String getCode() {
		return code;
	}

	/**
	 * @return the msg
	 */
	public String getMsg() {
		return msg;
	}

	/**
	 * @return the data
	 */
	public T getData() {
		return data;
	}

	/**
	 * @param code the code to set
	 */
	public void setCode(String code) {
		this.code = code;
	}

	/**
	 * @param msg the msg to set
	 */
	public void setMsg(String msg) {
		this.msg = msg;
	}

	/**
	 * @param data the data to set
	 */
	public void setData(T data) {
		this.data = data;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "JsonWrapper [code=" + code + ", msg=" + msg + ", data=" + data
				+ "]";
	}
}
